<template>
  <div class="table-main">
    <el-dialog
      @close="handMyClose"
      :append-to-body="true"
      title="汽车服务"
      :visible.sync="dialogVisible1"
      width="60%"
      :close-on-click-modal="false"
    >
      <div style="margin-top:50px;">
        <el-form ref="form" :model="form" label-width="120px" :rules="rules">
          <el-row :gutter="20" justify="center" type="flex">
            <el-col :span="16">
              <el-form-item label="商家店铺:" prop="shopId">
                <el-select
                  filterable
                  :disabled="isShow == 3"
                  v-model="form.shopId"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in findAllsList"
                    :key="item.id"
                    :label="item.shopName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" justify="center" type="flex">
            <el-col :span="16">
              <el-form-item label="车牌号:" prop="carNumber">
                <el-autocomplete
                  :disabled="isShow == 3"
                  class="inline-input"
                  v-model="form.carNumber"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入内容"
                  @select="handleSelect"
                ></el-autocomplete>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" justify="center" type="flex">
            <el-col :span="16">
              <el-form-item label="车辆型号:" prop="carType">
                <el-cascader
                  :disabled="isShow == 3"
                  @change="handData"
                  ref="myCascader"
                  :props="defaultParams"
                  :options="carTree"
                  v-model="form.carType"
                ></el-cascader>
                <el-button v-if="isShow != 3" type="text" @click="handEditCascader(item, index)">编辑</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" justify="center" type="flex" v-if="form.carType&&isShow != 3">
            <el-col :span="16">
              <el-button
                style="margin-bottom:10px"
                type="primary"
                size="small"
                icon="el-icon-plus"
                @click="handAdd()"
              >添加</el-button>
            </el-col>
          </el-row>

          <el-row
            :gutter="20"
            justify="center"
            type="flex"
            v-for="(item,index) in form.carMatterList"
            :key="item.id"
          >
            <el-col :span="8">
              <el-form-item label="项目名称:" prop="vipName">
                <el-input
                  :disabled="isShow == 3"
                  size="small"
                  placeholder="请输入内容"
                  v-model="item.matterKey"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目内容:" prop="vipName">
                <el-input
                  :disabled="isShow == 3"
                  size="small"
                  placeholder="请输入内容"
                  v-model="item.matterValue"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3" v-if="isShow != 3">
              <el-button type="text" @click="handDel(item, index)">删除</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="20" justify="center" type="flex">
            <el-col :span="16">
              <el-form-item label="保养图片:" prop="resourcesList">
                <el-upload
                  v-if="isShow != 3"
                  :on-change="onChange"
                  :headers="headers"
                  accept=".jpg, .png, .gif.svg, .bmp, .jpeg"
                  class="avatar-uploader"
                  :action="
                        $store.state.app.newUrl + '/admin/wxUser/uoloadfile'
                      "
                  :on-success="handSuccess2"
                  :before-upload="beforeAvatarUpload2"
                  list-type="picture-card"
                  v-loading="loadingUploda2"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-exceed="handleExceed"
                  :file-list="form.resourcesList"
                  :limit="4"
                  multiple
                >
                  <i class="el-icon-plus"></i>
                  <div slot="tip" class="el-upload__tip">最多只能上传4张图片</div>
                </el-upload>
                <div v-if="isShow == 3" class="img_item_box">
                  <img
                    v-for="imgItem in form.resourcesList"
                    :key="imgItem.name"
                    :src="imgItem.url"
                    class="avatar-uploader"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handFromSub('form')"
          :loading="bntLoading"
          v-if="isShow != 3"
        >确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-tree
        :data="carTree"
        show-checkbox
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        :render-content="renderContent"
        :props="defaultParams"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { imgSizi } from '@/utils/myUtils'
export default {
  name: 'SidebarLogo',
  components: {},
  watch: {
    isState(newObj) {
      this.isShow = newObj
    }
  },
  props: {
    isState: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      bntLoading: false,
      loading2: false,
      rules: {
        shopId: [{ required: true, message: '请选择商铺', trigger: 'change' }],
        carType: [
          { required: true, message: '请选择车辆型号', trigger: 'change' }
        ],
        carNumber: [
          { required: true, message: '请输入车牌号', trigger: 'blur' }
        ]
      },
      headers: {
        token: localStorage.getItem('mytoken') || ''
      },
      form: {
        vipDetails: [],
        resourcesList: [],
        carMatterList: []
      },
      shopStatusOptions: [],
      isShow: 0,
      imageUrl: '',
      dialogImageUrl: '',
      dialogVisible1: false,
      addressKeyword: '',
      activeName: 'first',
      dialogVisible: false,
      tipShow: false,
      restaurants: [],
      state1: '',
      carTree: [],
      defaultParams: {
        label: 'name',
        value: 'id',
        children: 'children'
      },
      carItemList: [],
      loadingUploda2: false,
      typeid: '',
      findAllsList: []
    }
  },
  async mounted() {
    this.findAllsList = (await this.$api.findShop()).data.data
    this.restaurants = (
      await this.$api.likeCarNumber({ CarNumber: '' })
    ).data.data
    this.restaurants.forEach(item => {
      item.value = item.carNumber
    })
    this.carTree = (await this.$api.carTypeTree()).data.data
    console.log(this.carTree, 'restaurantsrestaurantsrestaurantsrestaurants')
  },
  methods: {
    handAddFwb() {
      this.$nextTick(async () => {
        if (this.$refs.ceshifuwenben) {
          this.$refs.ceshifuwenben.setContent('')
          await this.$refs.ceshifuwenben.init()
        }
      })
    },
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span style="margin-left:20px;">
            <el-button
              size="mini"
              type="text"
              on-click={() => this.append(data)}
            >
              添加
            </el-button>
            <el-button
              size="mini"
              type="text"
              on-click={() => this.remove(node, data)}
            >
              删除
            </el-button>
          </span>
        </span>
      )
    },
    append(data) {
      this.$prompt('请输入邮箱', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '不能为空'
      })
        .then(({ value }) => {
          console.log(value, 'ww')
          this.$api
            .addCarType({
              carValue: value,
              pid: data.id,
              carLevel: data.weight + 1
            })
            .then(async res => {
              this.carTree = (await this.$api.carTypeTree()).data.data
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          })
        })
      console.log(data)
      // let id = Number(data.parentId)

      // const newChild = {
      //   id: id++,
      //   label: 'testtest',
      //   children: []
      // }
      // if (!data.children) {
      //   this.$set(data, 'children', [])
      // }
      // data.children.push(newChild)
    },

    remove(node, data) {
      // const parent = node.parent
      // const children = parent.data.children || parent.data
      // const index = children.findIndex(d => d.id === data.id)
      // children.splice(index, 1)
      this.$api
        .delCarType({
          id: data.id
        })
        .then(async res => {
          this.carTree = (await this.$api.carTypeTree()).data.data
        })
    },
    handEditCascader() {
      this.dialogVisible = true
    },
    handDel(item, index) {
      console.log(item, index)
      this.form.carMatterList.splice(index, 1)
    },
    handAdd() {
      this.form.carMatterList.push({
        matterKey: '',
        matterValue: ''
      })
    },
    async handData(val) {
      this.typeid = val[val.length - 1]
      let res = (await this.$api.typeIdByCarMatter({ typeid: this.typeid }))
        .data.data
      this.form.carMatterList = res
      this.form.carType = this.typeid
    },
    handleSelect(item) {
      console.log(item)
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants
      // 调用 callback 返回建议列表的数据
      console.log(results)

      cb(results)
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        )
      }
    },
    handDefault(val) {
      console.log(val)
    },
    changeInput() {
      this.$forceUpdate()
    },

    handEdit(item) {
      if (item.ifShow) {
        this.$set(item, 'ifShow', false)
      } else {
        this.$set(item, 'ifShow', true)
      }

      console.log(item, 'aaaaaaaaaa')
    },
    handEdit2(item) {
      this.$set(item, 'ifShow', true)
      console.log(this.form)
    },
    handSeleDel() {},
    uploadChange() {},
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制上传 4 张图片`)
    },
    handGetShop(id) {
      this.$api.selectCarInfoByIdCarInfo({ id }).then(res => {
        let imgurl = res.data.data.carImage.split(',')
        res.data.data.resourcesList = []
        imgurl.forEach((item, index) => {
          res.data.data.resourcesList.push({
            url: item,
            name: index + 'xx'
          })
        })
        this.form = res.data.data
        this.form.carType = this.form.carType + ''
        // this.form.carTypeid.push(this.form.carType + '')
        console.log(this.form.resourcesList, '查询轮播详情2', this.form)
      })
    },
    onChange() {},

    handSuccess2(res, file, fileList) {
      console.log(fileList, 'fileList')
      this.loadingUploda2 = false
      this.form.resourcesList = fileList
      this.form.carImage = []
    },
    beforeAvatarUpload2(file) {
      console.log(this.form.resourcesList)
      const isLt2M = this.form.resourcesList.length < 4
      if (!isLt2M) {
        this.$message.error('上传图片不能超过四张!')
      }
      return isLt2M
    },
    handMyClose() {
      this.$parent.closeFrom()
      for (let key in this.form) {
        this.form[key] = ''
      }
    },
    handFromSub(formName) {
      //1编辑
      if (this.isState == 1) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.form.carImage = []
            if (this.form.resourcesList.length == 0) {
              this.$message({
                message: '请上传保养图片',
                type: 'warning'
              })
            }
            this.form.resourcesList.forEach(item => {
              if (item.response) {
                item.response.message = JSON.parse(item.response.message)
                this.form.carImage.push(item.response.message.url)
              } else {
                this.form.carImage.push(item.url)
              }
            })
            this.form.CarMatter = this.form.carMatterList
            this.form.CarMatter.forEach(item => {
              item.carTypeId = this.form.carType
            })
            this.form.carImage = this.form.carImage.join(',')

            this.bntLoading = true
            this.$api
              .editCarInfo(this.form)
              .then(res => {
                this.dialogVisible1 = false
                this.$parent.init()
                console.log(res, '编辑', this.form)
                this.$message({
                  message: res.data.message,
                  type: 'success'
                })
                this.bntLoading = false
              })
              .finally(() => {
                this.bntLoading = false
              })
          } else {
            console.log('error submit!!')
            this.$message({
              message: '请完成表单录入'
            })
            this.bntLoading = false
            return false
          }
        })
      } else if (this.isState == 0) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.form.carImage = []
            this.form.resourcesList.forEach(item => {
              if (item.response) {
                item.response.message = JSON.parse(item.response.message)
                this.form.carImage.push(item.response.message.url)
              }
            })
            this.form.CarMatter = this.form.carMatterList
            this.form.CarMatter.forEach(item => {
              item.carTypeId = this.typeid
            })
            this.form.carType = this.typeid
            this.form.carImage = this.form.carImage.join(',')
            this.bntLoading = true
            this.$api
              .addCarInfo(this.form)
              .then(res => {
                this.dialogVisible1 = false
                this.bntLoading = false
                this.$parent.init()
                // this.$refs.form.resetFields()
                console.log(res, '添加vip,表单验证', this.form)
                this.$message({
                  message: res.data.message,
                  type: 'success'
                })
              })
              .finally(() => {
                this.bntLoading = false
              })
          } else {
            console.log('error submit!!')
            this.$message({
              message: '请完成表单录入'
            })
            return false
          }
        })
      }
    },

    // handSuccess(response, file, fileList) {
    //   console.log(response, file, fileList, '成功回调')
    //   this.form.shopImg = response.message
    // },
    handleRemove(file, fileList) {
      this.form.resourcesList = fileList
    },
    handlePictureCardPreview(file, fileList) {
      console.log(file, fileList)
    },
    handleClose() {
      this.dialogVisible = false
    },
    handMapShow() {
      this.dialogVisible = true
    },
    handleClick() {}
  }
}
</script>

<style lang="scss" scoped>
.img_item_box {
  width: 148px;
  height: 148px;
  img {
    width: 100%;
    height: 100%;
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.vipProjeck {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .pro_item {
    width: 20%;
  }
}
.map_btn {
  width: 82px;
  height: 22px;
  background: rgba(56, 173, 147, 1);
  border-radius: 4px;
  color: #fff;
  font-size: 14px;
  line-height: 22px;
  text-align: center;
  margin-top: 8px;
}
/deep/ .el-form-item__label {
  font-size: 14px;
  color: #000;
  font-weight: bold;
}
.form_box {
  width: 80%;
  margin: 0 auto;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #38ad93;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #38ad93;
  width: 56px;
  height: 44px;
  line-height: 44px;
  text-align: center;
}
.avatar {
  width: 56px;
  height: 44px;
  display: block;
}
.avatar-uploader-icon2 {
  font-size: 28px;
  color: #38ad93;
  width: 351px;
  height: 192px;
  line-height: 192px;
  text-align: center;
}
.avatar2 {
  width: 351px;
  height: 192px;
  display: block;
}
</style>
